package com.ny.controller;

import com.ny.entity.Devices;
import com.ny.entity.Result;
import com.ny.service.DeviceService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/device")
public class DeviceController {

    @Autowired
    private DeviceService deviceService;
    
    // 查询所有设备信息 http://localhost:8081/device/findAll
    @GetMapping("/findAll")
    public Result findAllDevices(){
        return Result.success(deviceService.findAll());
    }
    
    // 根据设备名称查询设备信息 http://localhost:8081/device/findByName?name=客厅主灯
    @GetMapping("/findByName")
    public Result findDeviceByName(@RequestParam String name){
        return Result.success(deviceService.findByName(name));
    }
    
    // 根据设备名称模糊查询设备信息 http://localhost:8081/device/findByNameLike?name=厨
    @GetMapping("/findByNameLike")
    public Result findDeviceByNameLike(@RequestParam String name){
        return Result.success(deviceService.findByNameLike(name));
    }
    
    // 添加设备信息http://localhost:8081/device/add?device_id: =&name: =&type: &status:&room:
    @PostMapping("/add")
    public Result addDevice(@RequestBody Devices device){
        Devices savedDevice = deviceService.addDevice(device);
        return Result.success(savedDevice);
    }
    //使用Postman添加设备的正确方法：
    //打开Postman
    //设置请求方法为POST
    //输入URL：http://localhost:8081/device/add
    //点击"Headers"选项卡，添加：
    //Key: Content-Type
    //Value: application/json
    //点击"Body"选项卡：
    //选择"raw"
    //选择"JSON"
    //在文本框中输入设备信息，例如：  {
    //     "device_id": 5,
    //     "name": "智能门锁",
    //     "type": "lock",
    //     "status": "on",
    //     "room": "大门"
    //   }


    // 更新设备信息http://localhost:8081/device/update
    @PutMapping("/update")
    public Result updateDevice(@RequestBody Devices device){
        Devices updatedDevice = deviceService.updateDevice(device);
        return Result.success(updatedDevice);
    }


    
    // 根据设备ID删除设备信息http://localhost:8081/device/deleteByDeviceId?deviceId=2
    @DeleteMapping("/deleteByDeviceId")
    public Result deleteDeviceById(@RequestParam int deviceId){
        int result = deviceService.deleteByDeviceId(deviceId);
        if (result > 0) {
            return Result.success("删除成功");
        } else {
            return Result.error("删除失败，未找到对应设备");
        }
    }
    

  //根据设备ID更新设备名称 http://localhost:8081/device/name/1?name=客厅主灯
    @PutMapping("/name/{deviceId}")
    public Result updateDeviceName(@PathVariable Integer deviceId, @RequestParam String name) {
        deviceService.updateDeviceNameByDeviceId(deviceId, name);
        return Result.success("设备名称更新成功");
    }
}